package com.jin.Es;

import com.alibaba.fastjson.JSON;
import com.jin.Es.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;

public class EsDemo04 {
    private RestHighLevelClient client;

    //1、创建SearchSourceBuilder对象
    private SearchSourceBuilder sourceBuilder;

    @Before
    public void init() {
        client = new RestHighLevelClient(RestClient.builder
                (new HttpHost("192.168.200.129", 9200, "http")));
    }

    @After
    public void close() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void highLight() throws IOException {
        // 1. 创建搜索请求
        SearchRequest request = new SearchRequest("user");
        // 2. 构建请求参数
        sourceBuilder = new SearchSourceBuilder();
        // 2.1 查询条件
        sourceBuilder.query(QueryBuilders.matchQuery("note","唱歌或者javaee"));
        // 2.2 构建高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("note");//高亮字段
        highlightBuilder.preTags("<span>");//前置标签
        highlightBuilder.postTags("</span>");//后置标签

        sourceBuilder.highlighter(highlightBuilder);

        request.source(sourceBuilder);

        //执行搜索
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            User user = JSON.parseObject(hit.getSourceAsString(), User.class);
            //高亮处理
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField note = highlightFields.get("note");
            Text[] noteFragments = note.getFragments();
            String notes = StringUtils.join(noteFragments);

            user.setNote(notes);
            System.out.println(user);
        }
    }
}
